package cn.itcast.server.handler;

import cn.itcast.message.RpcResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: LDeng
 * @Date: 2021-06-10 10:06
 */
@Slf4j
@ChannelHandler.Sharable
public class RpcResopnseMessageHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {

    //Key: SequenceId value: Promise对象， 接收结果
    //ConcurrentHashMap 是因为将来可能多个线程都会访问
    public static final Map<Integer,Promise<Object>> PROMISES=new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage msg) throws Exception {
        log.debug("服务器响应的消息是-->{}",msg);
        //拿到空的promise
        Promise<Object> promise = PROMISES.remove(msg.getSequenceId());//拿到并删除
        if(promise!=null){
            Object returnValue = msg.getReturnValue();
            Exception exceptionValue = msg.getExceptionValue();
            if(exceptionValue!=null){
                promise.setFailure(exceptionValue);
            }else{
                promise.setSuccess(returnValue);
            }

        }

    }
}
